﻿using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.IO;
using System.Linq;
using System.Text;

namespace Universe.Cache
{
    public class CacheSqlCeConnection
    {

        public string FileName { get; set; }
        public string Password { get; set; }

        public CacheSqlCeConnection(string fileName)
        {
            FileName = fileName;
        }

        public string CS
        {
            get
            {
                return
                    string.IsNullOrEmpty(Password)
                        ? string.Format("Data Source={0};Max Database Size=4091", FileName)
                        : string.Format("Data Source={0};Password={1};Max Database Size=1000", FileName, Password);

            }
        }

        private void ReInstall()
        {


            SqlCeEngine eng = new SqlCeEngine(CS);
            eng.CreateDatabase();

            foreach (string sql in SqlInstall)
            {
                using (SqlCeConnection con = new SqlCeConnection(CS))
                using (SqlCeCommand cmd = new SqlCeCommand(sql, con))
                {
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
            }

        }

        public void Configure()
        {
            if (!File.Exists(FileName))
                ReInstall();
        }

        private static readonly string[] SqlInstall =
            new[]
                {
                    @"
Create Table [Cache]
(
    [Id] binary(16) primary key,
    [Expired] datetime,
    [Stamp] image not null,
    [Value] image not null
)"
                    ,

                    @"
Create Index IX_Cache_Expired On [Cache]([Expired])
"
                    ,
                    @"
Create Table [Key]
(
    [Id] binary(16) primary key,
    [Prefix] nvarchar(" + CacheSqlCeStorage.PrefixLength + @"),
    [Suffix] NText
)"
                    ,
                    @"
Create Index IX_Key_Prefix On [Key]([Prefix])
"
                };




    }
}
